package com.v2future.sjt.collegecheckingattendance.rollcall;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.v2future.sjt.collegecheckingattendance.BaseFragment;
import com.v2future.sjt.collegecheckingattendance.LazyFragment;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.common.activity.DatePickerActivity;
import com.v2future.sjt.collegecheckingattendance.leave.CourseLeaveActivity;
import com.v2future.sjt.collegecheckingattendance.leave.bean.TeacherBean;
import com.v2future.sjt.collegecheckingattendance.rollcall.SelectClassActivity;
import com.v2future.sjt.collegecheckingattendance.rollcall.SelectSubjectActivity;
import com.v2future.sjt.collegecheckingattendance.rollcall.adapter.RollCallCourseAdapter;
import com.v2future.sjt.collegecheckingattendance.rollcall.adapter.SubjectAdapter;
import com.v2future.sjt.collegecheckingattendance.rollcall.bean.ClassBean;
import com.v2future.sjt.collegecheckingattendance.rollcall.bean.CourseBean;
import com.v2future.sjt.collegecheckingattendance.rollcall.bean.SubjectBean;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.CalculateTime;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.DateUtil;
import com.v2future.sjt.collegecheckingattendance.utils.IntentKey;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;
import com.v2future.sjt.collegecheckingattendance.widget.ListViewInScroll;
import com.v2future.sjt.collegecheckingattendance.widget.view.PullToRefreshView;

import org.w3c.dom.Text;

import java.io.Serializable;
import java.util.List;

/**
 * Created by minnie on 16/1/18.
 * 点名首页
 */
public class RollCallFragment extends LazyFragment implements View.OnClickListener,AdapterView.OnItemClickListener,PullToRefreshView.OnHeaderRefreshListener {

    Button startBtn;

    SubjectBean currentSelectSubject;

    ListViewInScroll rollCallCourseLv;

    List<SubjectBean> datalist;

    RollCallCourseAdapter adapter;

    PullToRefreshView pullView;

    LinearLayout selectTeacherLayout;
    LinearLayout selectDateLayout;
    LinearLayout selectCourseLayout;

    TextView teacherValueTv, dateValueTv, courseValueTv;

    /**
     * 选中的日期
     */
    private String selectDate;

    /**
     * 选择的老师
     */
    private TeacherBean teacherBean;

    /**
     * 选择的课程
     */
    private CourseBean.DataBean courseBean;

    /**
     * 点名的回复标识--老师选择
     */
    public static String TAG_ROLL_CALL_BACK_TEACHER = "rollcall_back_teacher";

    /**
     * 点名的回复标识--课程
     */
    public static String TAG_ROLL_CALL_BACK_COURSE = "rollcall_back_courese";


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_roll_call, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        pullView = (PullToRefreshView) view.findViewById(R.id.pullview1);
        pullView.setFooterViewVisibility(View.GONE);
        pullView.setOnHeaderRefreshListener(this);
        selectTeacherLayout = (LinearLayout) view.findViewById(R.id.layout_select_teacher);
        selectTeacherLayout.setOnClickListener(this);
        selectDateLayout = (LinearLayout) view.findViewById(R.id.layout_select_date);
        selectDateLayout.setOnClickListener(this);
        selectCourseLayout = (LinearLayout) view.findViewById(R.id.layout_select_course);
        selectCourseLayout.setOnClickListener(this);
        teacherValueTv = (TextView) view.findViewById(R.id.tv_select_teacher_value);
        dateValueTv = (TextView) view.findViewById(R.id.tv_select_date_value);
        String currentTime = DateUtil.getCurrentDateYMD();
        dateValueTv.setText(currentTime);
        selectDate = currentTime;
        courseValueTv = (TextView) view.findViewById(R.id.tv_select_course_value);
        rollCallCourseLv = (ListViewInScroll) view.findViewById(R.id.lv_rollcall_course);
        rollCallCourseLv.setOnItemClickListener(this);
        startBtn = (Button) view.findViewById(R.id.btn_start);
        startBtn.setOnClickListener(this);
    }

    @Override
    protected void lazyLoad() {
//        doGetTeacherCourse();
    }

    /**
     * 接受HomeActivity回送的onNewIntent
     *
     * @param intent
     */
    public void onNewIntent(Intent intent) {
        if (CourseLeaveActivity.BACKTAG_DATE_SELECT.equals(intent.getAction())) {
            selectDate = intent.getStringExtra(DatePickerActivity.TAG_SELECT_DATE);
            if (CalculateTime.compare_date(selectDate, DateUtil.getCurrentDateYMD()) <= 0) {
                dateValueTv.setText(selectDate);
            }
            else {
                getBaseActivity().showSimpleDialog("不能选择过去的日期");
            }
        }
        else if (RollCallFragment.TAG_ROLL_CALL_BACK_TEACHER.equals(intent.getAction())) {
            TeacherBean bean = (TeacherBean) intent.getSerializableExtra(SelectTeacherActivity.TAG_TEACHER);
            teacherBean = bean;
            teacherValueTv.setText(bean.getUserName());
        }
        else if (RollCallFragment.TAG_ROLL_CALL_BACK_COURSE.equals(intent.getAction())) {
            CourseBean.DataBean dataBean = (CourseBean.DataBean) intent.getSerializableExtra(SelectCourseActivity.TAG_COURSE);
            courseBean = dataBean;
            courseValueTv.setText("("+dataBean.getTime()+")" + dataBean.getCourseName());
        }
    }

    public void doGetTeacherCourse(){
        BaseRequestParams params = new BaseRequestParams(getBaseActivity(), getBaseActivity().formatUrl(Constants.TEACHE_COURSE));
        params.addQueryStringParameter("queryDate", DateUtil.getCurrentDateYMD());
        getBaseActivity().showTitleLoading();
        NetUtils.doGetRequest(getBaseActivity(), params, new NetTaskListener<SubjectResponeBean>() {

            /**
             * 数据获取完成
             *
             * @param result
             */
            @Override
            public void onSuccess(SubjectResponeBean result) {
                datalist = result.getData();
                refreshView();
                isPrepared = true;
            }

            /**
             * 位置网络错误
             */
            @Override
            public void onError() {

            }

            /**
             * 非正常状态的数据
             *
             * @param result
             */
            @Override
            public void onInterError(SubjectResponeBean result) {
                getBaseActivity().tip(result.getFailReason());
            }

            /**
             * 网络错误
             *
             * @param responseCode
             * @param responseMsg
             * @param errorResult
             */
            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                getBaseActivity().tip(responseMsg);
            }

            /**
             * 请求取消
             */
            @Override
            public void onCancelled() {

            }

            /**
             * 网络请求流程结束
             */
            @Override
            public void onFinished() {
                getBaseActivity().cancelTitleLoading();
                pullView.onHeaderRefreshComplete();
            }

            /**
             * 缓存获取完成
             *
             * @param result
             */
            @Override
            public void onSuccessCache(SubjectResponeBean result) {

            }
        });
    }

    private void refreshView() {
        adapter = new RollCallCourseAdapter(getBaseActivity(), datalist);
        rollCallCourseLv.setAdapter(adapter);
        if (datalist.size() == 0) {
            getBaseActivity().tip("暂无可以点名的课程");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        for (int i=0;i<datalist.size();i++) {
            datalist.get(i).setChecked(false);
        }
        datalist.get(position).setChecked(true);
        currentSelectSubject = datalist.get(position);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        doGetTeacherCourse();
    }

    /**
     * 教师点名课程数据
     */
    public class SubjectResponeBean extends BaseResponseBean implements Serializable {

        private List<SubjectBean> data;

        public List<SubjectBean> getData() {
            return data;
        }

        public void setData(List<SubjectBean> data) {
            this.data = data;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                if (null == teacherBean) {
                    getBaseActivity().showSimpleDialog("没有选择老师");
                    break;
                }
                if (TextUtils.isEmpty(selectDate)) {
                    getBaseActivity().showSimpleDialog("没有选择时间");
                    break;
                }
                if (null == courseBean) {
                    getBaseActivity().showSimpleDialog("没有选择课程");
                    break;
                }
                if (!teacherBean.getUserId().equals(courseBean.getTeacherId())) {
                    getBaseActivity().showSimpleDialog("老师和课程匹配有误");
                    break;
                }
                Intent intent_absentRollCall = new Intent(getBaseActivity(), RollCallAbsentV2Activity.class);
                //当前课程
                intent_absentRollCall.putExtra(IntentKey.COURSE, courseBean);
                //老师
                intent_absentRollCall.putExtra(IntentKey.TEACHER, teacherBean);
                //时间
                intent_absentRollCall.putExtra(IntentKey.TIME, selectDate);
                startActivity(intent_absentRollCall);
                break;
            //选择老师
            case R.id.layout_select_teacher:
                Intent intent_teacher = new Intent(getBaseActivity(), SelectTeacherActivity.class);
                startActivity(intent_teacher);
                break;
            //选择日期
            case R.id.layout_select_date:
                Intent dateIntent = new Intent(getBaseActivity(), DatePickerActivity.class);
                if (!TextUtils.isEmpty(selectDate)) {
                    dateIntent.putExtra(DatePickerActivity.TAG_SELECT_DATE, DateUtil.getCurrentDateYMD());
                }
                else {
                    dateIntent.putExtra(DatePickerActivity.TAG_SELECT_DATE, DateUtil.getCurrentDateYMD());
                }
                dateIntent.putExtra(DatePickerActivity.TAG_LEAVE_TYPE, DatePickerActivity.ROLLCALL);
                startActivity(dateIntent);
                break;
            //选择课程
            case R.id.layout_select_course:
                //选择课程前要判断是否已选择了教师
                if (teacherBean == null) {
                    getBaseActivity().tip("还没有选择老师");
                    break;
                }
                Intent intent_course = new Intent(getBaseActivity(), SelectCourseActivity.class);
                intent_course.putExtra(IntentKey.TEACHER, teacherBean);
                startActivity(intent_course);
                break;
            default:
                break;
        }
    }
}
